﻿using Microsoft.EntityFrameworkCore;
using Quartz;

namespace Application.Job
{
    public class ServerStatusJob : IJob
    {
        private readonly JobManagerDbContext _dbContext;
        public ServerStatusJob(JobManagerDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                var servers = await _dbContext.KeyValue.Where(s => s.Type == KeyValueType.Server).ToListAsync();
                var thisServer = servers.FirstOrDefault(s => s.Key == GlobalData.ServerKey);
                //1.更新本服务：updateTime
                if (thisServer == null)
                {
                    await _dbContext.KeyValue.AddAsync(new KeyValue { Key = GlobalData.ServerKey, Type = KeyValueType.Server });
                }
                else
                {
                    thisServer.UpdateTime = DateTime.Now;
                    var jobCount = await _dbContext.JobTask.CountAsync(s => s.ServerId == thisServer.Id && s.IsEnable);
                    thisServer.Value = $"任务数量：{jobCount}；操作系统：{Environment.OSVersion}；计算机名称：{Environment.MachineName}；当前用户：{Environment.UserName}；域：{Environment.UserDomainName}；";
                }

                //2.删除离线服务
                var outlines = servers.Where(s => s.UpdateTime < DateTime.Now.AddSeconds(-60)).ToList();
                _dbContext.RemoveRange(outlines);

                //3.离线服务的任务，设置ServerId = 0
                var inlines = servers.Where(s => !outlines.Select(s => s.Id).Contains(s.Id));
                var serverIds = inlines.Select(s => s.Id);
                var jobTasks = await _dbContext.JobTask.Where(s => !serverIds.Contains(s.ServerId)).ToListAsync();
                if (jobTasks.Has()) jobTasks.ForEach(s => s.ServerId = 0);
                await _dbContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                await Console.Out.WriteLineAsync(ex.Message);
            }

        }
    }
}
